<template>
  <div class="preview-img-wrap">
    <div v-loading="loading" class="preview-img">
      <span v-for="(item , index) in imgList" :key="index" @click="previewBigImg(index)">
        <el-image v-if="imgIdList.includes(item.id)" :src="item.url" fit="fill" lazy class="img" />
      </span>
    </div>
    <el-dialog
      v-dialogDrag
      title="图片预览"
      :visible.sync="dialogVisible"
      class="dialogStyleMiddle"
      :before-close="handleClose"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-carousel ref="previewImg" :interval="5000" arrow="always">
        <el-carousel-item v-for="(item , index) in imgList" :key="index" name="index">
          <el-image :src="item.url" fit="cover" style="height: 100%" />
        </el-carousel-item>
      </el-carousel>
    </el-dialog>
  </div>
</template>

<script>
// 图片下载
import { imgDownLoad } from '@/api/common/upload.js'
export default {
  name: 'Index',
  props: {
    imgIdList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      loading: false,
      imgList: [], // 图片list
      dialogVisible: false // 弹框标识
    }
  },
  watch: {
    imgIdList: {
      handler(val) {
        console.log(val)
        if (this.imgIdList.length > 0) {
          for (const i in this.imgIdList) {
            this.imgDownLoad(this.imgIdList[i])
          }
        }
      },
      deep: true, // 深度监听
      immediate: true // 初次监听即执行
    }
  },
  mounted() {
  },
  methods: {
    // 关闭弹框
    handleClose() {
      this.dialogVisible = false
    },
    // 图片回显
    imgDownLoad(id) {
      if (id && id !== null) {
        this.imgList = []
        const data = { id: id }
        this.loading = true
        imgDownLoad(data).then(res => {
          // 将从后台获取的图片流进行转换
          this.url = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
          const item = { url: this.url, id: id }
          // const imgList = []
          // imgList.push(item)
          this.imgList = new Set([...this.imgList, item])
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }
    },
    // 预览大图
    previewBigImg(index) {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.previewImg.setActiveItem(index)
      })
    }
  }
}

</script>

